﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using System.Timers;
using System.Windows.Forms;
using Api1;
using zwWitLink.Util;

namespace Camera
{
    public partial class CameraForm : Form
    {
        private int hHwnd;
        private const int port = 2000;
        public static int index = 0;
        public static int is_open = 0;// 摄像头是否开启
        public string[] list = new String[3]{"","",""};

        public CameraForm()
        { 
            InitializeComponent();
        }
        public struct videohdr_tag
        {
            public byte[] lpData;
            public int dwBufferLength;
            public int dwBytesUsed;
            public int dwTimeCaptured;
            public int dwUser;
            public int dwFlags;
            public int[] dwReserved;

        }
        public delegate bool CallBack(int hwnd, int lParam);
        ///   <summary>   
        ///   必需的设计器变量。   
        ///   </summary>   
        //private System.ComponentModel.Container components = null;
        [DllImport("avicap32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
        public static extern int capCreateCaptureWindowA([MarshalAs(UnmanagedType.VBByRefStr)]   ref   string lpszWindowName, int dwStyle, int x, int y, int nWidth, short nHeight, int hWndParent, int nID);
        [DllImport("avicap32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
        public static extern bool capGetDriverDescriptionA(short wDriver, [MarshalAs(UnmanagedType.VBByRefStr)]   ref   string lpszName, int cbName, [MarshalAs(UnmanagedType.VBByRefStr)]   ref   string lpszVer, int cbVer);
        [DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
        public static extern bool DestroyWindow(int hndw);
        [DllImport("user32", EntryPoint = "SendMessageA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
        public static extern int SendMessage(int hwnd, int wMsg, int wParam, [MarshalAs(UnmanagedType.AsAny)]   object lParam);
        [DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
        public static extern int SetWindowPos(int hwnd, int hWndInsertAfter, int x, int y, int cx, int cy, int wFlags);
        [DllImport("vfw32.dll")]
        public static extern string capVideoStreamCallback(int hwnd, videohdr_tag videohdr_tag);
        [DllImport("vicap32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
        public static extern bool capSetCallbackOnFrame(int hwnd, string s);

        private void OpenCapture()
        {
            if (is_open == 1)
            {
                return;
            }
            int intWidth = this.panel1.Width;
            int intHeight = this.panel1.Height;
            int intDevice = 0;
            string refDevice = intDevice.ToString();
            //创建视频窗口并得到句柄
            hHwnd = CameraForm.capCreateCaptureWindowA(ref   refDevice, 1342177280, 0, 0, 1024, 800, this.panel1.Handle.ToInt32(), 0);
            if (CameraForm.SendMessage(hHwnd, 0x40a, intDevice, 0) > 0)
            {
                CameraForm.SendMessage(this.hHwnd, 0x435, -1, 0);
                CameraForm.SendMessage(this.hHwnd, 0x434, 0x42, 0);
                CameraForm.SendMessage(this.hHwnd, 0x432, -1, 0);
                CameraForm.SetWindowPos(this.hHwnd, 1, 0, 0, intWidth, intHeight, 6);
                is_open = 1;
            }
            else
            {
                is_open = 0;
                CameraForm.DestroyWindow(this.hHwnd);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (is_open == 0)
            {
                this.OpenCapture();
            }
            //停止视频注销视频句柄

        }

        private void button2_Click(object sender, EventArgs e)
        {
            //停止视频注销视频句柄
            CameraForm.SendMessage(this.hHwnd, 0x40b, 0, 0);
            CameraForm.DestroyWindow(this.hHwnd);
        }

        //截图
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                CameraForm.SendMessage(this.hHwnd, 0x41e, 0, 0);
                IDataObject obj1 = Clipboard.GetDataObject();
                if (obj1.GetDataPresent(typeof(Bitmap)))
                {

                    Image image1 = (Image)obj1.GetData(typeof(Bitmap));
                    //string dir = Application.StartupPath + "c:\\wamp\\data\\face";

                    string face_dir = "c:\\wamp\\www\\anke\\data\\face\\" + DateTime.Now.ToString("yyyyMMdd");
                    if (!Directory.Exists(face_dir))
                    {
                        Directory.CreateDirectory(face_dir);
                    }
                    string name = Path.Combine(@face_dir, DateTime.Now.ToString("yyyyMMddhhmmss") + new Random().Next(10000) + ".jpeg");
                   // MessageBox.Show(name);
                    image1.Save(name, ImageFormat.Jpeg);

                    if (index % 3 == 0)
                    {
                        list[0] = name;
                        pictureBox1.Image = image1;//读取bmp2到picturebox
                    }
                    else if (index % 3 == 1)
                    {
                        list[1] = name;
                        pictureBox2.Image = image1;//读取bmp2到picturebox
                    }
                    else if (index % 3 == 2)
                    {
                        list[2] = name;
                        pictureBox3.Image = image1;//读取bmp2到picturebox
                    }
                    index++;
                    new System.Drawing.Bitmap(image1).Dispose();
                }
            }
            catch (Exception ex)
            {
                //一般都是图片路径的问题
                MessageBox.Show(ex.ToString());
            }
        }
        public void show_pic(PictureBox pictureBox, int index)
        {                     
            try
            {
                CameraForm.SendMessage(this.hHwnd, 0x41e, 0, 0);
                IDataObject obj1 = Clipboard.GetDataObject();
                if (obj1.GetDataPresent(typeof(Bitmap)))
                {

                    Image image1 = (Image)obj1.GetData(typeof(Bitmap));
                    string dir = Application.StartupPath + "\\data\\face";
                    string face_dir = "c:\\wamp\\www\\anke\\data\\face\\" + DateTime.Now.ToString("yyyyMMdd") ;
                    if (!Directory.Exists(face_dir)) {
                        Directory.CreateDirectory(face_dir); 
                    }
                    string name=DateTime.Now.ToString("yyyyMMddhhmmss") + new Random().Next(10000) + ".jpeg";
                    string path = Path.Combine(@face_dir, name);
                    image1.Save(path, ImageFormat.Jpeg);

                    String temp = "";// 图片特征码
                    //保存图片到本地
                    if (zwForm.IsBlackImage.Equals("1"))//黑白
                    {
                         ImageConver.GrayImage(new Bitmap(image1), 1).Save(@"c:\\wamp\\www\\anke\\data\\face\\test.jpeg");
                         //黑白图片特征码
                         temp = zwForm.GetDetect(@"c:\\wamp\\www\\anke\\data\\face\\test.jpeg")[0];
                    }
                    else {
                        //彩图特征码
                        temp = zwForm.GetDetect(@path)[0];
                    }
                    if (temp == null) {
                        MessageBox.Show("当前人脸模型有误!请重新录入");
                        return;
                    }
                    zwForm.faceUrl[index] = path;
                    zwForm.face[index] = temp.ToString();
                    if (zwForm.face[index].Length < 1000)
                    {
                        MessageBox.Show("当前人脸模型有误!请重新录入");
                        return;
                    }                         
                   // 保存图片到主机
                    zwForm.upload_image(path, name);
                    list[index] = path;
                    pictureBox.Image = image1;//读取bmp2到picturebox                    
                    new System.Drawing.Bitmap(image1).Dispose();
                }
            }
            catch (Exception ex)
            {
                //一般都是图片路径的问题
                MessageBox.Show(ex.ToString());
            }        
        }

        private void button4_Click(object sender, EventArgs e)
        {
            CameraForm.SendMessage(this.hHwnd, 0x40b, 0, 0);
            CameraForm.DestroyWindow(this.hHwnd);
            System.Environment.Exit(0);
        }
        /// <summary>
        /// 清除照片 和剪切板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            Clipboard.Clear();
            index = 0;
            list = new String[3];
            pictureBox1.Image = null;
            pictureBox2.Image = null;
            pictureBox3.Image = null;
        }

        System.Timers.Timer mytime;
        public void hiddentextBox(TextBox t)
        {
            mytime = new System.Timers.Timer(1500);
            mytime.Elapsed += new ElapsedEventHandler((s, e) => theout(s, e, t));
            mytime.AutoReset = false;
            mytime.Enabled = true;
            mytime.Start();
        }

        private object theout(object s, ElapsedEventArgs e, TextBox t)
        {
            t.Visible = false;
            return null;
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

            this.OpenCapture();
            show_pic(pictureBox1, 0);
            Clipboard.Clear();
            Clipboard.SetText(string.Join(",", list));

        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {
            this.OpenCapture();
            show_pic(pictureBox2, 1);
            Clipboard.Clear();
            Clipboard.SetText(string.Join(",", list));

        }

        private void pictureBox3_Click(object sender, EventArgs e)
        {
            this.OpenCapture();
            show_pic(pictureBox3, 2);
            Clipboard.Clear();
            Clipboard.SetText(string.Join(",", list));
        }

        private void CameraForm_Load(object sender, EventArgs e)
        {
            this.OpenCapture();
        }
     
        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }


        private void CameraForm_Closing(object sender, FormClosedEventArgs e)
        {
            zwForm.camera_instance = null;
            is_open = 0;
            CameraForm.SendMessage(this.hHwnd, 0x40b, 0, 0);
            CameraForm.DestroyWindow(this.hHwnd);

        }
    }
}
